﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using RuoVea.DynamicWebApi;
using RuoVea.ExDto;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.OmiApi.Log.Entitys;
using SqlSugar;
using System.ComponentModel;

namespace RuoVea.OmiApi.Log.Service;

/// <summary>
/// 系统差异日志服务 🔷
/// </summary>
[ApiExplorerSettings(GroupName = "system")]
public class SysLogDiffService : IApplicationService
{
    private readonly SugarRepository<SysLogDiff> _sysLogDiffRep;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sysLogDiffRep"></param>
    public SysLogDiffService(SugarRepository<SysLogDiff> sysLogDiffRep) => _sysLogDiffRep = sysLogDiffRep;


    /// <summary>
    /// 获取差异日志分页列表
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取差异日志分页列表")]
    public async Task<PageResult<SysLogDiff>> GetPagesAsync(PageParam data)
    {
        var BeginTime = data.BeginTime != null; 
        if (data.EndTime.HasValue)
        {
            data.EndTime = data.EndTime.Value.Date.AddDays(1).AddSeconds(-1);
        }

        return await _sysLogDiffRep.AsQueryable()
            .WhereIF(data.BeginTime.HasValue, u => u.CreateTime >= data.BeginTime)
            .WhereIF(data.EndTime.HasValue, u => u.CreateTime <= data.EndTime)
            .OrderBy(u => u.CreateTime, OrderByType.Desc)
            .ToPageAsync(data.PageNo, data.PageSize);
    }
    /// <summary>
    /// 根据主键查询🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<SysLogDiff> GetDataAsync([FromQuery] EntityBaseId data)
    {
        var model = await _sysLogDiffRep.GetByIdAsync(data.Id);
        if (model == null) return null;
        return model.Adapt<SysLogDiff>();
    }
    /// <summary>
    /// 清空差异日志
    /// </summary>
    /// <returns></returns>
    [HttpDelete]
    [DisplayName("清空差异日志")]
    public bool Clear()
    {
       return _sysLogDiffRep.AsSugarClient().DbMaintenance.TruncateTable<SysLogDiff>();
    }

    /// <summary>
    /// 按时间范围删除日志（可选添加）
    /// </summary>
    [HttpPost("clear-by-time")]
    [DisplayName("按时间范围删除日志")]
    public async Task<int> ClearByTimeRange([FromQuery] DateTime? beginTime, [FromQuery] DateTime? endTime)
    {
        if (beginTime == null && endTime == null)
            throw new ArgumentException("请至少提供一个时间条件");

        // 处理结束时间
        if (endTime.HasValue)
        {
            endTime = endTime.Value.Date.AddDays(1).AddSeconds(-1);
        }

        return await _sysLogDiffRep.AsDeleteable()
            .WhereIF(beginTime.HasValue, u => u.CreateTime >=beginTime.Value)
            .WhereIF(endTime.HasValue, u => u.CreateTime <= endTime.Value)
            .ExecuteCommandAsync();
    }
}